The switch statement in C++ is used for multi-way branching, allowing to execute different code blocks based on the value of an expression or variable. It provides a cleaner and more efficient alternative to using a series of if-else if statements when have multiple cases to consider. Here's the basic syntax of the switch statement:
switch (expression) {
case constant1:
// Code to execute when expression == constant1
break; // Optional break statement to exit the switch block
case constant2:
// Code to execute when expression == constant2
break;
// ... more case statements ...
default:
// Code to execute when none of the cases match
}
expression: A value or expression whose result is used to determine which case to execute.
case constant1, case constant2, etc.: Labels that represent specific constant values or expressions to be compared against expression.
break: An optional keyword used to exit the switch block after a case has been executed. Without break, control will "fall through" to subsequent cases until a break statement is encountered.
default: An optional case that is executed when none of the other cases match the expression. It acts as the "default" choice.
Here's a simple example of a switch statement:
#include <iostream>
int main() {
int choice;
std::cout << "Enter a number (1-3): ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "chose option 1." << std::endl;
break;
case 2:
std::cout << "chose option 2." << std::endl;
break;
case 3:
std::cout << "chose option 3." << std::endl;
break;
default:
std::cout << "Invalid choice." << std::endl;
}
return 0;
}
In this example, the value of choice entered by the user is compared against the cases 1, 2, and 3, and the corresponding code block is executed. If none of the cases matches, the default block is executed.
question
question2